<template>
  <a-modal
    :title="title"
    :open="visible"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="产品名称" name="productName">
        <a-input v-model:value="form.productName" placeholder="请输入产品名称" />
      </a-form-item>

      <a-form-item label="检验标准" name="inspectionStandard">
        <a-input v-model:value="form.inspectionStandard" placeholder="请输入检验标准" />
      </a-form-item>

      <a-form-item label="周期" name="cycle">
        <a-input v-model:value="form.cycle" placeholder="请输入周期" />
      </a-form-item>

      <a-form-item label="用量" name="dosage">
        <a-input v-model:value="form.dosage" placeholder="请输入用量" />
      </a-form-item>

      <a-form-item label="单价" name="unitPrice">
        <a-input-number
          v-model:value="form.unitPrice"
          placeholder="请输入单价"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="产品类型" name="productType">
        <a-select v-model:value="form.productType" placeholder="请选择产品类型">
          <a-select-option v-for="item in productTypeOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue'
import type { Product } from '@/types/product'
import { productTypeOptions } from '@/types/product'
import * as productApi from '@/api/product'

interface Props {
  visible: boolean
  formData?: Partial<Product>
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: () => ({})
})

const emit = defineEmits<Emits>()

// 表单相关
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<Partial<Product>>({
  productId: undefined,
  productName: '',
  inspectionStandard: '',
  cycle: '',
  dosage: '',
  unitPrice: undefined,
  productType: undefined
})

// 表单标题
const title = computed(() => {
  return props.formData.productId ? '编辑产品' : '新增产品'
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ],
  productType: [
    { required: true, message: '请选择产品类型', trigger: 'change' }
  ]
}

// 监听formData变化，填充表单
watch(() => props.formData, (newVal) => {
  if (newVal) {
    // 使用 Object.assign 确保所有字段都被正确赋值，包括 productId
    Object.assign(form, {
      productId: newVal.productId,
      productName: newVal.productName || '',
      inspectionStandard: newVal.inspectionStandard || '',
      cycle: newVal.cycle || '',
      dosage: newVal.dosage || '',
      unitPrice: newVal.unitPrice,
      productType: newVal.productType
    })
  } else {
    // 重置表单
    Object.assign(form, {
      productId: undefined,
      productName: '',
      inspectionStandard: '',
      cycle: '',
      dosage: '',
      unitPrice: undefined,
      productType: undefined
    })
  }
}, { immediate: true, deep: true })

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formRef.value?.resetFields()
  }
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    if (form.productId) {
      // 编辑：调用更新接口
      await productApi.updateProduct({ ...form, productId: form.productId })
    } else {
      // 新增：调用新增接口
      await productApi.addProduct(form)
    }

    message.success(`${title.value}成功`)
    emit('success')
  } catch (error) {
    message.error(`${title.value}失败`)
    console.error(`${title.value}失败:`, error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script>